# 使用回调记录日志

from langchain.callbacks import FileCallbackHandler
# from langchain.chains import LLMChain 该方法已废弃，使用prompt | llm的方法取代
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from loguru import logger
from openaiConfigurations import openai_api_key, openai_api_base
logfile = "output.log"
logger.add(logfile, colorize = True, enqueue = True)
# FileCallbackHandler的输出已经格式化过，这里直接使用
handler = FileCallbackHandler(logfile)
llm = ChatOpenAI(openai_api_key = openai_api_key, openai_api_base = openai_api_base, callbacks = [handler], verbose = True)
prompt = PromptTemplate.from_template("1 + {number} = ")
# 这条链将同时向标准输出打印（verbose = True）并写入output.log
chain = prompt | llm
answer = chain.invoke({"number": 1}).content
print(answer)
logger.info(answer)